package com.coder.shop.rpc.service.impl;

import com.coder.common.annotation.BaseService;
import com.coder.common.base.BaseServiceImpl;
import com.coder.shop.dao.mapper.ShopGoodsTypeMapper;
import com.coder.shop.dao.mapper.ShopGoodsTypeSpecMapper;
import com.coder.shop.dao.model.ShopGoodsType;
import com.coder.shop.dao.model.ShopGoodsTypeExample;
import com.coder.shop.dao.model.ShopGoodsTypeSpecExample;
import com.coder.shop.rpc.api.ShopGoodsTypeService;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* ShopGoodsTypeService实现
* @Author liuzhimin
* @Date Created by liuzhimin on 2018/4/24.
* @Description
*/
@Service
@Transactional
@BaseService
public class ShopGoodsTypeServiceImpl extends BaseServiceImpl<ShopGoodsTypeMapper, ShopGoodsType, ShopGoodsTypeExample> implements ShopGoodsTypeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShopGoodsTypeServiceImpl.class);

    @Autowired
    ShopGoodsTypeMapper shopGoodsTypeMapper;
    
    @Autowired
    ShopGoodsTypeSpecMapper  shopGoodsTypeSpecMapper;
    
    /**
	 * 查询商品分类（树形结构）
	 */
	@Override
	public List<ShopGoodsType> findTreeList() {
		List<ShopGoodsType> list = selectByExample(new ShopGoodsTypeExample());
		return getChildrenList(0,list);
	}
	
	private static List<ShopGoodsType> getChildrenList(Integer pId,List<ShopGoodsType> list){
		List<ShopGoodsType> children = null;
		for (int i = 0; i < list.size(); i++) {
			if(children==null) {
				children = new ArrayList<ShopGoodsType>();
			}
			ShopGoodsType next = list.get(i);
			if(next.getpId().intValue() == pId.intValue()) {
				children.add(next);
				list.remove(i);
				next.setChildren(getChildrenList(next.getId(),list));
			}
		}
		return children;
	}

	@Transactional
	@Override
	public int addGoodsType(ShopGoodsType shopGoodsType, Integer[] specIds) {
		int row = insertSelective(shopGoodsType);
		if(specIds != null && specIds.length>0) {
			row = shopGoodsTypeSpecMapper.insertBatch(shopGoodsType.getId(), specIds);
		}
		return row;
	}

	@Override
	public int updateGoodsType(ShopGoodsType shopGoodsType, Integer[] specIds) {
		int row = updateByPrimaryKeySelective(shopGoodsType);
		
		ShopGoodsTypeSpecExample example = new ShopGoodsTypeSpecExample();
		example.createCriteria().andTypeIdEqualTo(shopGoodsType.getId());
		shopGoodsTypeSpecMapper.deleteByExample(example);
		
		if(specIds != null && specIds.length>0) {
			row = shopGoodsTypeSpecMapper.insertBatch(shopGoodsType.getId(), specIds);
		}
		
		return row;
	}

}